package com.tyc.c13;

import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;
import org.apache.coyote.ProtocolHandler;
import org.apache.coyote.http11.Http11Nio2Protocol;
import org.springframework.context.annotation.Configuration;

import javax.servlet.ServletContainerInitializer;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CountDownLatch;

/**
 * 创建内嵌的Tomcat
 */
public class ApplicationC13 {
    public static void main(String[] args) throws IOException, LifecycleException, InterruptedException {
        // 1.创建Tomcat对象
        Tomcat tomcat = new Tomcat();
        tomcat.setBaseDir("tomcat");
        // 2.创建项目文件夹 docBase
        File docBase = Files.createTempDirectory("boot.").toFile();
        docBase.deleteOnExit();
        // 3.创建Tomcat项目:Context
        Context context = tomcat.addContext("", docBase.getAbsolutePath());
        // 4.添加Servlet
        context.addServletContainerInitializer(new ServletContainerInitializer() {
            @Override
            public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
                servletContext.addServlet("helloServlet",new HelloServlet()).addMapping("/hello");
            }
        }, Collections.emptySet());
        // 5.启动Tomcat
        tomcat.start();
        // 6.创建连接器、设置监听端口
        Connector connector = new Connector("HTTP/1.1");
        connector.setPort(8088);

        tomcat.setConnector(connector);
        new CountDownLatch(1).await();
    }
}
